package com.example.userdemo.util;

import cn.hutool.core.collection.CollUtil;
import com.example.userdemo.entity.Position;

import java.util.List;

/**
 * @Description 计算问题字符占比工具类
 * @Author liqinglin
 * @Date 2023/11/28 17:26
 */

public class CalculateUtil {
    /**
     * 用于计算校验问题字符数占比
     * @param positionList
     * @param length
     * @return
     */
    public static Double CalculateIssueRatio(List<Position> positionList, Long length){
        if (CollUtil.isEmpty(positionList)){
            return 0.0;
        }
        //按照起点升序排列
        positionList.sort((o1, o2) -> {
            int num1 = o1.getPositionStart() - o2.getPositionStart();
            return num1 == 0 ? o1.getPositionEnd() - o2.getPositionEnd() : num1;
        });

        long sumLength = 0;
        //当前最右侧已经计算长度下标指针
        int index = positionList.get(0).getPositionStart();

        //遍历求问题文本长度和
        for (Position position : positionList){
            if (position.getPositionEnd() >= index){
                sumLength += (position.getPositionEnd() - Math.max(index, position.getPositionStart()));
                index = position.getPositionEnd();
            }
        }
        System.out.println(sumLength);
        //四舍五入保留两位小数
        double ratio = sumLength / (double) length;
        return Math.round(ratio * 100.0) / 100.0;
    }
}
